package com.larry.mr2.reducejoin;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class ReduceJoinReducer extends Reducer<Text,OrderProduct,OrderProduct, NullWritable> {

    private List<OrderProduct> list = new ArrayList<>();
    private OrderProduct pd = new OrderProduct();
    @Override
    protected void reduce(Text key, Iterable<OrderProduct> values, Reducer<Text, OrderProduct, OrderProduct, NullWritable>.Context context) throws IOException, InterruptedException {

        for (OrderProduct value : values) {
            if (value.getFlag().equals("order")){
                OrderProduct orderProduct = new OrderProduct();
                try {
                    BeanUtils.copyProperties(orderProduct,value);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
                list.add(orderProduct);
            }else {
                try {
                    BeanUtils.copyProperties(pd,value);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        for (OrderProduct orderProduct : list) {
            orderProduct.setPname(pd.getPname());
            context.write(orderProduct,NullWritable.get());
        }

        list.clear();

    }
}
